<template>
  <div class="app-container">
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList" :search-params="searchParams">
    </SearchForm>
    <el-card class="box-card">
      <!-- 订单状态标签页 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待支付" name="pending"></el-tab-pane>
        <el-tab-pane label="已支付" name="paid"></el-tab-pane>
        <el-tab-pane label="已发货" name="shipped"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
        <el-tab-pane label="退款中" name="refunding"></el-tab-pane>
        <el-tab-pane label="已退款" name="refunded"></el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
      </el-tabs>

      <!-- 订单列表 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="订单ID" align="center" width="80">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>

        <el-table-column label="订单号" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.order_no }}
          </template>
        </el-table-column>

        <el-table-column label="用户信息" align="center" width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.user">
              <div>ID: {{ scope.row.user.id }}</div>
              <div>{{ scope.row.user.nickname || scope.row.user.username }}</div>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>

        <el-table-column label="商品信息" align="center" min-width="350">
          <template slot-scope="scope">
            <div v-if="scope.row.items && scope.row.items.length > 0">
              <div v-for="(item, index) in scope.row.items" :key="index" class="product-item">
                <div class="product-img" v-if="getProductDetail(item)">
                  <el-image
                    style="width: 60px; height: 60px"
                    :src="getProductDetail(item).product.post_url"
                    fit="cover"
                    :preview-src-list="[getProductDetail(item).product.post_url]"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
                <div class="product-info">
                  <div class="product-title" v-if="getProductDetail(item)">
                    {{ getProductDetail(item).product.title || '商品详情' }}
                  </div>
                  <div class="product-price">
                    <span>{{ item.count }} x ¥{{ getProductPrice(item) }}</span>
                    <span class="total-price">= ¥{{ (item.count * getProductPrice(item)).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>

        <el-table-column label="订单金额" align="center" width="120">
          <template slot-scope="scope">
            <div>总金额: ¥{{ scope.row.amount }}</div>
            <div>支付金额: ¥{{ scope.row.payment_amount || 0 }}</div>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="物流信息" align="center" width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.express_company">
              <div>{{ scope.row.express_company }}</div>
              <div>{{ scope.row.express_no }}</div>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.create_time }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template slot-scope="scope">
            <!-- 查看详情按钮 -->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="primary"-->
<!--              @click="handleDetail(scope.row)"-->
<!--            >-->
<!--              详情-->
<!--            </el-button>-->

            <!-- 发货按钮 - 仅对已支付订单显示 -->
            <el-button
              v-if="scope.row.status === 'paid'"
              size="mini"
              type="success"
              @click="handleShip(scope.row)"
            >
              发货
            </el-button>

            <!-- 取消订单按钮 - 仅对待支付或已支付订单显示 -->
            <el-button
              v-if="scope.row.status === 'pending' || scope.row.status === 'paid'"
              size="mini"
              type="warning"
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>

            <!-- 退款按钮 - 仅对已支付订单显示 -->
            <el-button
              v-if="scope.row.status === 'paid'"
              size="mini"
              type="danger"
              @click="handleRefund(scope.row)"
            >
              退款
            </el-button>

            <!-- 审核退款按钮 - 仅对退款中订单显示 -->
            <el-button
              v-if="scope.row.status === 'refunding'"
              size="mini"
              type="danger"
              @click="handleRefundConfirm(scope.row)"
            >
              审核退款
            </el-button>

            <!-- 删除按钮 - 仅对已取消或已退款订单显示 -->
            <el-button
              v-if="scope.row.status === 'cancelled' || scope.row.status === 'refunded'"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="page-box">
        <el-pagination
            background
            :current-page="pageNo"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="changePageSize"
            @current-change="changePageNo"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog title="订单发货" :visible.sync="shipDialogVisible" width="500px">
      <el-form :model="shipForm" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ currentOrder.order_no }}</span>
        </el-form-item>
        <el-form-item label="物流公司" prop="express_company">
          <el-select
            v-model="shipForm.express_company"
            placeholder="请选择物流公司"
            filterable
            allow-create
            default-first-option
          >
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
            <el-option label="百世快递" value="百世快递" />
            <el-option label="京东物流" value="京东物流" />
            <el-option label="邮政快递" value="邮政快递" />
            <el-option label="天天快递" value="天天快递" />
            <el-option label="德邦快递" value="德邦快递" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="宅急送" value="宅急送" />
          </el-select>
          <div class="form-tip">支持手动输入新的物流公司名称</div>
        </el-form-item>
        <el-form-item label="物流单号" prop="express_no">
          <el-input v-model="shipForm.express_no" placeholder="请输入物流单号"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="shipForm.remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmShip">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog title="订单退款" :visible.sync="refundDialogVisible" width="500px">
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ currentOrder.order_no }}</span>
        </el-form-item>
        <el-form-item label="订单金额">
          <span>¥{{ currentOrder.payment_amount || currentOrder.amount }}</span>
        </el-form-item>
        <el-form-item label="退款金额" prop="refund_amount">
          <el-input-number v-model="refundForm.refund_amount" :min="0" :max="currentOrder.payment_amount || currentOrder.amount" :precision="2" :step="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="退款原因" prop="refund_reason">
          <el-input v-model="refundForm.refund_reason" type="textarea" rows="3" placeholder="请输入退款原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRefund">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审核退款对话框 -->
    <el-dialog title="审核退款" :visible.sync="refundConfirmDialogVisible" width="500px">
      <el-form :model="refundConfirmForm" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ currentOrder.order_no }}</span>
        </el-form-item>
        <el-form-item label="订单金额">
          <span>¥{{ currentOrder.payment_amount || currentOrder.amount }}</span>
        </el-form-item>
        <el-form-item label="退款原因">
          <span>{{ currentOrder.refund_reason || '无' }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="approve">
          <el-radio-group v-model="refundConfirmForm.approve">
            <el-radio :label="true">同意退款</el-radio>
            <el-radio :label="false">拒绝退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款金额" prop="refund_amount" v-if="refundConfirmForm.approve">
          <el-input-number v-model="refundConfirmForm.refund_amount" :min="0" :max="currentOrder.payment_amount || currentOrder.amount" :precision="2" :step="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="refund_remark">
          <el-input v-model="refundConfirmForm.refund_remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundConfirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRefundConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from '@/api'
import crud from "@/mixins/crud";

// 订单状态枚举
const OrderStatusEnum = {
  PENDING_PAYMENT: 'pending',
  PAID: 'paid',
  REFUNDED: 'refunded',
  REFUNDING: 'refunding',
  COMPLETED: 'completed',
  CANCELLED: 'cancelled',
  SHIPPED: 'shipped',
  PENDING_RECEIPT: 'pending_receipt'
}

// 订单状态文本映射
const OrderStatusTextMap = {
  [OrderStatusEnum.PENDING_PAYMENT]: '待支付',
  [OrderStatusEnum.PAID]: '已支付',
  [OrderStatusEnum.REFUNDED]: '已退款',
  [OrderStatusEnum.REFUNDING]: '退款中',
  [OrderStatusEnum.COMPLETED]: '已完成',
  [OrderStatusEnum.CANCELLED]: '已取消',
  [OrderStatusEnum.SHIPPED]: '已发货',
  [OrderStatusEnum.PENDING_RECEIPT]: '待收货'
}

// 订单状态标签类型映射
const OrderStatusTypeMap = {
  [OrderStatusEnum.PENDING_PAYMENT]: 'warning',
  [OrderStatusEnum.PAID]: 'success',
  [OrderStatusEnum.REFUNDED]: 'info',
  [OrderStatusEnum.REFUNDING]: 'danger',
  [OrderStatusEnum.COMPLETED]: 'success',
  [OrderStatusEnum.CANCELLED]: 'info',
  [OrderStatusEnum.SHIPPED]: 'primary',
  [OrderStatusEnum.PENDING_RECEIPT]: 'primary'
}

export default {
  name: 'OrderManagement',
  mixins: [crud],
  data() {
    return {
      request: http.order,
      searchList: [
        { label: '订单号', prop: 'order_no', name: 'input' },
        { label: '用户ID', prop: 'user_id', name: 'input' }
      ],
      activeTab: 'all',
      searchParams: {
        status: '',
        order_no: '',
        user_id: ''
      },

      // 发货对话框
      shipDialogVisible: false,
      shipForm: {
        express_company: '',
        express_no: '',
        remark: ''
      },

      // 退款对话框
      refundDialogVisible: false,
      refundForm: {
        refund_amount: 0,
        refund_reason: ''
      },

      // 审核退款对话框
      refundConfirmDialogVisible: false,
      refundConfirmForm: {
        approve: true,
        refund_amount: 0,
        refund_remark: ''
      },
      // 当前操作的订单
      currentOrder: {}
    }
  },
  methods: {
    // 获取商品详情
    getProductDetail(item) {
      if (!item.product_detail) return null;
      try {
        return typeof item.product_detail === 'string'
          ? JSON.parse(item.product_detail)
          : item.product_detail;
      } catch (e) {
        console.error('解析商品详情失败', e);
        return null;
      }
    },

    // 获取商品价格
    getProductPrice(item) {
      const detail = this.getProductDetail(item);
      if (!detail) return 0;
      return detail.product.price || 0;
    },

    // 处理标签页点击
    handleTabClick() {
      // 根据选中的标签页设置查询条件
      switch (this.activeTab) {
        case 'all':
          this.searchParams.status = ''
          break
        case 'pending':
          this.searchParams.status = OrderStatusEnum.PENDING_PAYMENT
          break
        case 'paid':
          this.searchParams.status = OrderStatusEnum.PAID
          break
        case 'shipped':
          this.searchParams.status = OrderStatusEnum.SHIPPED
          break
        case 'completed':
          this.searchParams.status = OrderStatusEnum.COMPLETED
          break
        case 'refunding':
          this.searchParams.status = OrderStatusEnum.REFUNDING
          break
        case 'refunded':
          this.searchParams.status = OrderStatusEnum.REFUNDED
          break
        case 'cancelled':
          this.searchParams.status = OrderStatusEnum.CANCELLED
          break
        default:
          this.searchParams.status = ''
      }
      this.onSearch()
    },
    // 获取订单状态文本
    getOrderStatusText(status) {
      return OrderStatusTextMap[status] || '未知状态'
    },

    // 获取订单状态标签类型
    getOrderStatusType(status) {
      return OrderStatusTypeMap[status] || 'info'
    },

    // 查看订单详情
    handleDetail(row) {
      this.$router.push({ path: `/order/detail/${row.id}` })
    },

    // 处理发货
    handleShip(row) {
      this.currentOrder = row
      this.shipForm = {
        express_company: '',
        express_no: '',
        remark: ''
      }
      this.shipDialogVisible = true
    },

    // 确认发货
    confirmShip() {
      if (!this.shipForm.express_company) {
        this.$message.error('请选择物流公司')
        return
      }
      if (!this.shipForm.express_no) {
        this.$message.error('请输入物流单号')
        return
      }

      const data = {
        id: this.currentOrder.id,
        status: OrderStatusEnum.SHIPPED,
        express_company: this.shipForm.express_company,
        express_no: this.shipForm.express_no,
        remark: this.shipForm.remark
      }

      http.order.update(this.currentOrder.id, data).then(() => {
        this.$message.success('发货成功')
        this.shipDialogVisible = false
        this.getList()
      }).catch(error => {
        this.$message.error(error.message || '发货失败')
      })
    },

    // 处理取消订单
    handleCancel(row) {
      this.$confirm('确认取消该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.order.cancel({ id: row.id }).then(() => {
          this.$message.success('订单已取消')
          this.getList()
        }).catch(error => {
          this.$message.error(error.message || '取消订单失败')
        })
      }).catch(() => {})
    },

    // 处理退款
    handleRefund(row) {
      this.currentOrder = row
      this.refundForm = {
        refund_amount: row.payment_amount || row.amount,
        refund_reason: '管理员主动退款'
      }
      this.refundDialogVisible = true
    },

    // 确认退款
    confirmRefund() {
      if (this.refundForm.refund_amount <= 0) {
        this.$message.error('退款金额必须大于0')
        return
      }

      const data = {
        id: this.currentOrder.id,
        refund_reason: this.refundForm.refund_reason,
        refund_amount: this.refundForm.refund_amount
      }

      http.order.refund(data).then(() => {
        this.$message.success('退款申请已提交')
        this.refundDialogVisible = false
        this.getList()
      }).catch(error => {
        this.$message.error(error.message || '退款申请失败')
      })
    },

    // 处理审核退款
    handleRefundConfirm(row) {
      this.currentOrder = row
      this.refundConfirmForm = {
        approve: true,
        refund_amount: row.payment_amount || row.amount,
        refund_remark: ''
      }
      this.refundConfirmDialogVisible = true
    },

    // 提交退款审核
    submitRefundConfirm() {
      const data = {
        id: this.currentOrder.id,
        refund_remark: this.refundConfirmForm.refund_remark,
        refund_amount: this.refundConfirmForm.approve ? this.refundConfirmForm.refund_amount : 0
      }

      http.order.refundConfirm(data).then(() => {
        this.$message.success(this.refundConfirmForm.approve ? '退款已审核通过' : '退款已拒绝')
        this.refundConfirmDialogVisible = false
        this.getList()
      }).catch(error => {
        this.$message.error(error.message || '审核退款失败')
      })
    },

    // 处理删除订单
    handleDelete(row) {
      this.$confirm('确认删除该订单吗? 删除后将无法恢复!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.order.delete(row.id).then(() => {
          this.$message.success('订单已删除')
          this.getList()
        }).catch(error => {
          this.$message.error(error.message || '删除订单失败')
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.filter-container {
  padding-bottom: 10px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
}

.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;

  &:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
  }

  .product-img {
    margin-right: 10px;
    width: 60px;
    height: 60px;
    flex-shrink: 0;

    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 20px;
    }
  }

  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .product-title {
      font-size: 13px;
      margin-bottom: 5px;
      color: #303133;
      word-break: break-all;
      text-align: left;
    }

    .product-price {
      font-size: 12px;
      color: #606266;
      text-align: left;

      .total-price {
        margin-left: 5px;
        color: #f56c6c;
        font-weight: bold;
      }
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  padding-top: 4px;
}
</style>
